<template>
  <view class="wrapper">
    <view class="top">
      <view class="back" @tap="toBack">
        <image src="../../images/aliang/navigation.png" mode="widthFix"></image>
      </view>
      <text class="title">圈子介绍</text>
      <text class="right-btn" @tap="save">保存</text>
    </view>
    <view class="input-wrapper">
      <text ref="input" id="upFile" style="display: none"></text>
      <quill-editor
        class="editor"
        v-model="messages"
        ref="myQuillEditor"
        @blur="onEditorBlur"
        @focus="onEditorFocus"
        @ready="onEditorReady"
        :options="editorOption"
        style="height: auto"
      >
        <span slot="toolbar" class="ql-formats" id="dealRe" @click="dealRe(1)">
          <img
            src="../../images/editor/icon (7).png"
            class="ql-re1"
            alt=""
            srcset=""
          />{{ scrollHeight }}
        </span>
        <span slot="toolbar" class="ql-formats" id="dealRe1" @click="dealRe(2)">
          <img
            src="../../images/editor/icon (6).png"
            alt=""
            srcset=""
            class="ql-re2"
          />
        </span>
      </quill-editor>
    </view>
    <!-- 链接 -->
    <view class="layer" v-show="layer == 1" v-cloak>
      <view class="mask" @click="tolayer(0)"></view>
      <view class="layer-content" style="width: 76%">
        <view class="info">
          <h3>添加链接</h3>
          <view class="input-box">
            <input
              type="text"
              placeholder="标题"
              v-model="link.title"
              :focus="autofocus"
            />
            <input type="text" placeholder="http://" v-model="link.url" />
          </view>
          <view class="line"></view>
          <view class="btn">
            <span @click="tolayer(0)">取消</span>
            <view class="line"></view>
            <span @click="addText">插入</span>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import * as qiniu from "qiniu-js";
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
const toolbarOptions = [
  // ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ["image"],
  ["video"],
  ["link"],
  ["bold"],
  ["underline"], // toggled buttons
  // ['blockquote', 'code-block'],
  [{ header: 1 }], // custom button values
  [{ header: 2 }], // custom button values
  ["blockquote"],
  // [{'header': [1,2,3]}],               // custom button values
  // [{'list': '1,2ordered'}, {'list': 'bullet'}],
  [{ list: "bullet" }],
  // [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
  // [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  // [{'direction': 'rtl'}],                         // text direction

  // [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
  // [{'header': [1, 2, 3, 4, 5, 6, false]}],

  // [{'color': []}, {'background': []}],          // dropdown with defaults from theme
  // [{'font': []}],
  // [{'align': []}],
  // ['clean']                                         // remove formatting button
];
export default {
  data() {
    var that = this;
    return {
      title: "富文本编辑器测试",
      messages: "", //绑定数据
      history: [],
      isHide: false,
      layer: 0,
      autofocus: false,
      editorOption: {
        //配置
        modules: {
          toolbar: {
            toolbar: "#toolbar",
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  let length = this.quill.getSelection().index;
                  if (!length) {
                    let length = this.quill.getLength();
                  }
                  this.quill.blur();
                  var input = document.createElement("input"); //创建元素
                  input.type = "file"; //添加file类型
                  input.multiple = "multiple"; //添加file类型
                  input.accept = "image/*";
                  document.getElementById("upFile").appendChild(input);
                  input.click();
                  input.onchange = (event) => {
                    that.zh_uploadFile_change(event, "image", length);
                  };
                } else {
                  this.quill.format("image", false);
                }
              },
              video: function (value) {
                if (value) {
                  let length = this.quill.getSelection().index;
                  if (!length) {
                    let length = this.quill.getLength();
                  }
                  this.quill.blur();
                  var input = document.createElement("input"); //创建元素
                  input.type = "file"; //添加file类型
                  input.multiple = "multiple"; //添加file类型
                  // input.accept=".mp4";
                  input.accept = "video/*";
                  document.getElementById("upFile").appendChild(input);
                  input.click();
                  input.onchange = (event) => {
                    that.zh_uploadFile_change(event, "video", length);
                  };
                } else {
                  this.quill.format("image", false);
                }
              },
              link: function (value) {
                this.quill.blur();
                if (value) {
                  that.layer = 1;
                  that.autofocus = true;
                } else {
                  this.quill.format("link", false);
                }
              },
            },
          },
          history: {
            delay: 1000,
            maxStack: 500,
          },
        },
      },
      link: {
        title: "",
        url: "",
      },
      scrollHeight: 0,
      changeValue: "",
    };
  },
  components: {
    quillEditor,
  },
  mounted() {
    this.editorOption.initButton && this.editorOption.initButton();
    this.hintGetFun();
    this.$nextTick(() => {
      // 工具栏手动插入
      var dealRe = document.getElementById("dealRe");
      var dealRe1 = document.getElementById("dealRe1");
      document.getElementsByClassName("ql-toolbar")[0].appendChild(dealRe);
      document.getElementsByClassName("ql-toolbar")[0].appendChild(dealRe1);

      // 设置样式
      let ql1 = document.getElementsByClassName("ql-underline")[0];
      let ql2 = document.getElementsByClassName("ql-bold")[0];
      let ql3 = document.getElementsByClassName("ql-blockquote")[0];
      let ql4 = document.getElementsByClassName("ql-header")[0];
      let ql5 = document.getElementsByClassName("ql-header")[1];
      let ql6 = document.getElementsByClassName("ql-list")[0];
      let ql7 = document.getElementsByClassName("ql-link")[0];
      let ql8 = document.getElementsByClassName("ql-image")[0];
      let ql9 = document.getElementsByClassName("ql-video")[0];
      let ql10 = document.getElementsByClassName("ql-re1")[0];
      let ql11 = document.getElementsByClassName("ql-re2")[0];
      // console.log(this.openApp.phone)
      if (this.openApp.phone == "Android") {
        ql1.style.cssText = "width: 36px; height:36px;";
        ql2.style.cssText = "width: 36px; height:36px;";
        ql3.style.cssText = "width: 36px; height:36px;";
        ql4.style.cssText = "width: 36px; height:36px;";
        ql5.style.cssText = "width: 36px; height:36px;";
        ql6.style.cssText = "width: 36px; height:36px;";
        ql7.style.cssText = "width: 36px; height:36px;";
        ql8.style.cssText = "width: 36px; height:36px;";
        ql9.style.cssText = "width: 36px; height:36px;";
        ql10.style.cssText = "width: 36px; height:36px;padding:8px";
        ql11.style.cssText = "width: 36px; height:36px;padding:8px";
      } else {
      }
    });
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
    isSave() {
      return this.changeValue == this.messages;
    },
  },
  props: {
    deconstruct: {
      type: String,
      required: false,
      default: "",
    },
  },
  watch: {
    messages(newVal, val) {
      this.$nextTick(() => {
        var quill = this.$refs.myQuillEditor.quill;
        var qlContainer = document.getElementsByClassName("ql-container")[0];
        var qlEditor = document.getElementsByClassName("ql-editor")[0];
        uni.pageScrollTo({
          scrollTop: qlEditor.scrollHeight + 100,
          duration: 50,
        });
        qlEditor.scrollTop = qlEditor.scrollHeight;
      });
    },
    scrollHeight() {
      // return document.getElementsByClassName('ql-container')[0].scrollHeight
      return document.documentElement.scrollTop || document.body.scrollTop || 0;
    },
  },
  onLoad(option) {
    this.messages = uni.getStorageSync("text");
    this.changeValue = uni.getStorageSync("text");
    this.id = option.id;
  },
  created() {
    this.content = this.escapeStringHTML(this.deconstruct);
    if (this.deconstruct === "") {
      this.history.push("");
    }
  },
  methods: {
    hintGetFun() {
      this.$nextTick(function () {
        this.$refs.myQuillEditor.quill.enable(true);
        this.$refs.myQuillEditor.quill.blur();
      });
    },
    onEditorBlur() {
      //失焦事件
      // console.log("blur", this.messages);
      let u = navigator.userAgent;
      let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isIOS) {
        setTimeout(() => {
          const scrollHeight =
            document.documentElement.scrollTop || document.body.scrollTop || 0;
          window.scrollTo(0, Math.max(scrollHeight - 1, 0));
        }, 200);
      }
    },
    onEditorFocus() {
      var quill = this.$refs.myQuillEditor.quill;
      var qlContainer = document.getElementsByClassName("ql-container")[0];
      var qlEditor = document.getElementsByClassName("ql-editor")[0];
      uni.pageScrollTo({
        scrollTop: qlEditor.scrollHeight + 100,
        // scrollTop: 9999,
        duration: 50,
      });
    },
    onEditorReady() {
      //进来执行
    },
    escapeStringHTML(str) {
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },
    handleSuccess(res, type, length, i) {
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, type, res);
        // 调整光标到最后
        quill.setSelection(length + i);
      } else {
        uni.showToast({
          title: "图片插入失败",
          duration: 2000,
          icon: "none",
        });
      }
      // quill.enable(true);
    },
    zh_uploadFile_change(evfile, type, length) {
      uni.showLoading({
        title: "加载中",
      });
      if (evfile.target.files.length == 0) {
        // layer.close(loading)
        uni.hideLoading();
        uni.showToast({
          title: "上传失败，请重新上传",
          duration: 2000,
          icon: "none",
        });
        return;
      }
      var fileArr = [];
      for (var item of evfile.target.files) {
        fileArr.push(item);
      }
      var fileArr = fileArr.filter((item) => {
        if (
          (item.type.indexOf("image") == -1 && type == "image") ||
          (item.type.indexOf("video") == -1 && type == "video")
        ) {
          uni.showToast({
            title: "上传文件类型错误",
            duration: 2000,
            icon: "none",
          });
          return false;
        }
        return true;
      });
      if (fileArr.length == 0) {
        return;
      }
      this.request({
        url: "h5/home/uploadApplication",
        method: "post",
        header: {
          "content-type": "application/json;charset=UTF-8",
          "api-client": "72e0fee8172411ea995200163e05ff66",
          "api-version": this.globalData.apiVersion,
          "Source-Type": 7,
          token: uni.getStorageSync("token"),
        },
        data: {},
      }).then((res) => {
        var res = res.data;
        var uptoken = res.data.upToken;
        // console.log("file",file)
        var key = null; // 上传后文件资源名以设置的 key 为主，如果 key 为 null 或者 undefined，则文件资源名会以 hash 值作为资源名。
        var region = res.data.region.split(".");
        let config = {
          useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
          region: qiniu.region[region[2]], // ,当为 null 或 undefined 时，自动分析上根据具体提示修改上传地区传域名区域
        };
        var i = 0;
        fileArr.map((item) => {
          if (item.size / 1024 / 1024 > 100) {
            uni.showToast({
              title: "上传文件不能超过100M",
              duration: 2000,
              icon: "none",
            });
            return;
          } else {
            i++;
            let putExtra = {
              fname: item.name, //文件原文件名
              params: {}, //用来放置自定义变量
              // mimeLimit:"",
              // mimeLimit: this.mimeLimit,
              // 	mimeType: this.mimeType //用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
            };
            var observable = qiniu.upload(item, key, uptoken, putExtra, config);
            observable.subscribe({
              next: (result) => {
                // 主要用来展示进度
              },
              error: (errResult) => {
                // layer.close(loading)
                uni.showToast({
                  title: errResult,
                  duration: 2000,
                  icon: "none",
                });
                uni.hideLoading();
              },
              complete: (result) => {
                var url = encodeURI(
                  res.data.qiniuDomain +
                    "/" +
                    result.key +
                    (this.type == "file" ? `?attname=${item.name}` : "")
                );
                this.handleSuccess(url, type, length, i);
                uni.hideLoading();
              },
            });
          }
        });
      });
    },
    tolayer(n) {
      this.layer = n;
    },
    addText() {
      let quill = this.$refs.myQuillEditor.quill;
      let length = quill.getLength();
      quill.insertText(length, this.link.title, "link", this.link.url);
      this.tolayer(0);
    },
    dealRe(n) {
      let quill = this.$refs.myQuillEditor.quill;
      quill.blur();
      // console.log(this.quill)
      if (n == 1) {
        quill.history.undo();
        quill.blur();
      } else {
        quill.history.redo();
        quill.blur();
      }
    },
    toBack() {
      // console.log(this.isSave)
      var that = this;
      if (!this.isSave) {
        uni.showModal({
          title: "提示",
          confirmText: "保存",
          content: "修改内容尚未保存，是否保存",
          success: function (res) {
            if (res.confirm) {
              that.save();
            } else if (res.cancel) {
              uni.navigateBack({
                delta: 1,
              });
            }
          },
        });
      } else {
        window.history.go(-1);
      }
    },
    save() {
      if (
        this.changeValue ==
          '<p style="margin: 0;" data-mce-style="margin: 0;"><br></p>' ||
        this.changeValue == '<p style="margin:0"><br data-mce-bogus="1"></p>'
      ) {
        this.changeValue = `<p style="margin: 0px;" data-mce-style="margin: 0px;">欢迎来到商界精英圈子，在这里你可以：</p><p style="margin: 0px;" data-mce-style="margin: 0px;"><br data-mce-bogus="1"></p><p style="margin: 0px;" data-mce-style="margin: 0px;">1、抢先知晓商界精英智慧，大量结交商界精英人脉</p><p style="margin: 0px;" data-mce-style="margin: 0px;"><br data-mce-bogus="1"></p><p style="margin: 0px;" data-mce-style="margin: 0px;">2、与各位老板在圈子内交流互动、共同进步 </p><p style="margin: 0px;" data-mce-style="margin: 0px;"><br data-mce-bogus="1"></p><p style="margin: 0px;" data-mce-style="margin: 0px;">3、打造良心商业生态，撮合生意，实现互利共赢<br data-mce-bogus="1"></p>`;
      }
      let token = uni.getStorageSync("token");
      this.request({
        url: "h5/orgCircle/updateFriends",
        method: "POST",
        header: {
          "content-type": "application/json;charset=UTF-8",
          "api-client": "72e0fee8172411ea995200163e05ff66",
          "api-version": this.globalData.apiVersion,
          "Source-Type": 7,
          token: token,
        },
        data: {
          id: this.id,
          circlePromotion: this.changeValue, //标签数组
        },
      }).then((res) => {
        // console.log(res, '发现圈子')
        if (res.data.code == 200) {
          uni.showToast({
            title: "保存成功",
            duration: 1500,
            icon: "none",
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 500);
          // this.findList = res.data.data
        } else {
          uni.showToast({
            title: res.data.msg,
            duration: 2000,
            icon: "none",
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
html,
body {
  height: calc(100% - 16px);
}
.wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  // 顶部
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 106rpx;
    padding: 0 29rpx 0 30rpx;
    background: rgb(248, 248, 248);
    color: rgb(0, 0, 0);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    .back {
      width: 60rpx;
      image {
        width: 31rpx;
        vertical-align: middle;
        display: inline-block;
      }
    }
    .title {
      font-size: 36rpx;
      font-family: PingFangSC, PingFangSC-Medium;
      font-weight: 500;
      text-align: center;
      color: #111111;
    }
    .right-btn {
      width: 60rpx;
      font-size: 28rpx;
      font-family: PingFangSC, PingFangSC-Regular;
      font-weight: 400;
      text-align: right;
      color: #0f6ede;
    }
  }

  .input-wrapper {
    display: flex;
    flex-direction: row;
    width: 100%;
    // margin: px2rem(5) 0;
    box-sizing: border-box;
    margin-top: 106rpx;
    /deep/ .editor {
      width: 100%;
      .ql-container.ql-snow {
        position: relative;
        top: 0px;
        border: none;
        font-size: 16px;
        padding: 116rpx 36rpx 64rpx;
        min-height: 440rpx;
        .ql-tooltip {
          &.ql-hidden {
            display: none;
          }
          font-size: 13px;
          padding: 5px 6px;
          display: flex;
          flex-wrap: wrap;
          margin: 0 36rpx;
          .ql-preview {
            max-width: 183px;
          }
        }
        .ql-editor.ql-blank::before {
          left: 0;
        }
      }
      .ql-toolbar.ql-snow {
        padding: 0;
        text-align: left;
        overflow-x: auto;
        white-space: nowrap;
        width: 100%;
        box-sizing: border-box;
        position: fixed;
        left: 0;
        right: 0;
        bottom: -2rpx;
        padding-bottom: 20rpx;
        border: none;
        background: #fff;
        z-index: 9999;
        .ql-formats {
          margin-right: 0;
          box-sizing: border-box;
          .ql-bold,
          .ql-underline,
          .ql-blockquote,
          .ql-header,
          .ql-list,
          .ql-link,
          .ql-image,
          .ql-video,
          .ql-re1,
          .ql-re2 {
            width: 80rpx;
            height: 80rpx;
            border: none;
            background: #fff;
          }
          .ql-re1,
          .ql-re2 {
            width: 70rpx;
            height: 70rpx;
            padding: 18rpx;
          }
          .ql-active {
            background: #eee !important;
          }
        }
        .ql-picker.ql-size {
          width: 70px;
        }
        .ql-picker.ql-header {
          width: 82px;
        }
        button {
          height: auto;
          width: 32px;
          padding: 3px 7px;
        }
      }
      .ql-editor.ql-blank:before {
        font-style: normal;
      }
      .ql-editor ol,
      .ql-editor ul {
        padding-left: 10px;
      }
      .ql-editor ol li:not(.ql-direction-rtl),
      .ql-editor ul li:not(.ql-direction-rtl) {
        padding-left: 20px;
      }

      .ql-snow .ql-tooltip a.ql-action::after {
        margin-left: 8px;
      }
    }
    .field {
      flex: 1;
      border: 1px solid pink;
    }
  }
}
.layer {
  .mask {
    position: fixed;
    display: inline-block;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    background: rgba(51, 51, 51, 0.08);
    z-index: 999;
  }
  .layer-content {
    background: #f8f8f2;
    width: 70%;
    border-radius: 10px;
    -webkit-box-shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.06);
    box-shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.06);
    position: absolute;
    top: 45%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    z-index: 999;
    // padding:0 54px;
    .info {
      text-align: center;
      h3 {
        font-size: 16px;
        font-family: PingFang SC;
        color: #333333;
        line-height: 28px;
        padding: 6px 0;
      }
      .input-box {
        width: 90%;
        border-radius: 8px;
        border: 1px solid #cacaca;
        margin: auto;
        overflow: hidden;
        text-align: left;
      }
      input {
        width: 101%;
        padding: 6px 6px 6px 4px;
        height: 33px;
        background: #ffffff;
        box-sizing: border-box;
        font-size: 14px;
        border: none;
        &:first-child {
          border-bottom: 1px solid #cacaca;
        }
      }
      & > .line {
        width: 100%;
        height: 1px;
        background: #cacaca;
        margin: 10px 0 0;
      }
      .btn {
        height: 40px;
        line-height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #4a47f5;
        span {
          flex: 1;
          display: inline-block;
        }
        & > .line {
          width: 1px;
          height: 100%;
          background: #cacaca;
        }
      }
    }
  }
}
</style>
